﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SRF.Data.SQLParser
{
    /// <summary>
    /// 默认解析程序
    /// </summary>
    public class DefaultSQLParser : ISQLParser
    {
        readonly string ParamPattern = @"{0}[\w._]+";
        readonly string SectionPattern = @"\{[\s\S]+?\}";
        readonly char VarEdges = '$';

        public string Parse(string sql, Func<string, object> getParameterValue, char parameterToken)
        {
            //TODO:解析参数获取值来替换
            Regex strParamRegex = new Regex(string.Format(@"\{0}[\w\.]+\{0}", VarEdges));
            sql = strParamRegex.Replace(sql, (m) =>
            {
                var value = getParameterValue(m.Value.Trim(VarEdges));
                return value == null ? m.Value : value.ToString();
            });
            StringBuilder sqlBuilder = new StringBuilder(sql);
            //根据参数是否为空 删除{}的语句段
            var sectionRegex = new Regex(SectionPattern);
            var paraRegex = new Regex(string.Format(ParamPattern, parameterToken));
            foreach (Match segMatch in sectionRegex.Matches(sqlBuilder.ToString()))
            {
                //查找语句段里边的参数
                foreach (Match paraMatch in paraRegex.Matches(segMatch.Value))
                {
                    var paraname = paraMatch.Value.TrimStart(parameterToken);
                    var value = getParameterValue(paraname);
                    if (value == null || string.IsNullOrEmpty(value.ToString()))
                    {
                        sqlBuilder.Replace(segMatch.Value, "");
                    }
                }
            }

            sqlBuilder.Replace('{', ' ').Replace('}', ' ');

            return sqlBuilder.ToString();
        }

        static DefaultSQLParser _instance;

        public static ISQLParser Get()
        {
            if (_instance == null)
            {
                _instance = new DefaultSQLParser();
            }
            return _instance;
        }
    }
}